﻿using HDLogCenter.Infrastructure.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;

namespace HDLogCenter.Infrastructure.Redis
{
    public  class AlertRuleRedisService
    {
        /// <summary>
        /// Redis 缓存 Key
        /// </summary>
        private readonly string _alertRuleKey = "alert:rules";

        private readonly ILogger<AlertRuleRedisService> _logger;

        public AlertRuleRedisService(ILogger<AlertRuleRedisService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取所有告警规则
        /// </summary>
        public List<AlertRuleModel> GetAllAlertRules()
        {
            try
            {
                var rules = RedisHelper.Get<List<AlertRuleModel>>(_alertRuleKey);
                return rules ?? new List<AlertRuleModel>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Redis 获取告警规则异常: {Message}", ex.Message);
                return new List<AlertRuleModel>();
            }
        }

        /// <summary>
        /// 设置告警规则（覆盖写入）
        /// </summary>
        public void SetAlertRules(List<AlertRuleModel> rules)
        {
            try
            {
                if (rules == null || rules.Count == 0)
                {
                    _logger.LogWarning("尝试设置空的告警规则列表到 Redis");
                    return;
                }

                RedisHelper.Set(_alertRuleKey, rules, 24 * 60 * 60); // 过期时间 1 天
                _logger.LogInformation("成功写入 {Count} 条告警规则到 Redis", rules.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Redis 设置告警规则异常: {Message}", ex.Message);
            }
        }
    }
}
